package counter.com.common;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import counter.com.baomidou.entity.Userinfo;
import counter.com.baomidou.service.IUserinfoService;
import counter.com.configuration.TokenManager;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Map;

//@Component
public class ProductServiceInterceptor implements HandlerInterceptor {
    static final String PASSURL = "/userinfo/login";

    @Autowired
    IUserinfoService userinfoService;
    private static String token = "token";

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        Map<String, String> cookies = CookieUtil.getCookies(request);
        if (cookies.size() > 0) {
            String token = cookies.get(ProductServiceInterceptor.token);
            TokenManager cookieManager = TokenManager.getInstance();
            //取得用户名称
            String username = cookieManager.getUsernameByToken(token);
            if (username != null) {
                LambdaQueryWrapper<Userinfo> wrapper = new LambdaQueryWrapper();
                wrapper.eq(Userinfo::getUsername, username);
                Userinfo user = userinfoService.getOne(wrapper);
                if (user == null) {
                    response.sendError(403, "错误的session信息");
                    cookieManager.removeToken(token);
                    System.out.println("错误的session信息");
                    return false;
                } else {
                    return true;
                }
            } else {
                response.sendError(403, "没有在Cookie中找到token");
                System.out.println("没有在Cookie中找到token");
                return false;
            }
        } else {
            response.sendError(403, "不存在cookie");
            System.out.println("不存在cookie");
            return false;
        }
    }
}
